const util = require('../../utils/util');
const MessageService = require('../../service/system/message.service');

async function createMessage(ctx) {
	const { userId } = util.decodeToken(ctx); // 从 token 获取当前用户ID
	const { title, type, content, sendType, deptIds = [], userIds = [], createtype = 1 } = ctx.request.body;

	// 参数校验
	if (!title || !type || !content || !sendType) {
		return util.fail(ctx, '消息标题、类型、内容和发送类型不能为空');
	}
	if (![1013001, 1013002].includes(type)) {
		return util.fail(ctx, '无效的消息类型');
	}
	if (![1015001, 1015002, 1015003].includes(sendType)) {
		return util.fail(ctx, '无效的发送类型');
	}
	if (sendType === 1015003 && (!deptIds || deptIds.length === 0)) {
		return util.fail(ctx, '部门发送类型必须提供部门ID');
	}
	if (sendType === 1015002 && (!userIds || userIds.length === 0)) {
		return util.fail(ctx, '指定用户发送类型必须提供用户ID');
	}

	const result = await MessageService.createMessage({
		title,
		type,
		content,
		senderId: userId,
		sendType,
		deptIds,
		userIds,
		createtype,
	});

	util.success(ctx, result);
}

async function listMessages(ctx) {
	const { page = 1, limit = 10, title, type, isPublished } = ctx.query;

	const result = await MessageService.listMessages({
		page: +page,
		limit: +limit,
		title,
		type: type ? +type : undefined,
		isPublished,
	});

	util.success(ctx, result);
}
async function updateMessage(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { id, title, type, content, sendType, deptIds = [], userIds = [], createtype = 1 } = ctx.request.body;

	// 参数校验
	if (!id) {
		return util.fail(ctx, '消息ID不能为空');
	}
	if (!title || !type || !content || !sendType) {
		return util.fail(ctx, '消息标题、类型、内容和发送类型不能为空');
	}
	if (![1013001, 1013002].includes(type)) {
		return util.fail(ctx, '无效的消息类型');
	}
	if (![1015001, 1015002, 1015003].includes(sendType)) {
		return util.fail(ctx, '无效的发送类型');
	}
	if (sendType === 1015003 && (!deptIds || deptIds.length === 0)) {
		return util.fail(ctx, '部门发送类型必须提供部门ID');
	}
	if (sendType === 1015002 && (!userIds || userIds.length === 0)) {
		return util.fail(ctx, '指定用户发送类型必须提供用户ID');
	}

	const result = await MessageService.updateMessage({
		id,
		title,
		type,
		content,
		senderId: userId,
		sendType,
		deptIds,
		userIds,
		createtype,
	});

	util.success(ctx, result);
}
async function deleteMessage(ctx) {
	const { ids } = ctx.request.body;

	// 参数校验
	if (!ids || !Array.isArray(ids) || ids.length === 0) {
		return util.fail(ctx, '请提供有效的消息ID数组');
	}

	const result = await MessageService.deleteMessage(ids);

	util.success(ctx, result);
}

async function getMessageById(ctx) {
	const { id } = ctx.params;
	if (!id) return util.fail(ctx, '消息 ID 无效');
	const message = await MessageService.getMessageById(Number(id));
	if (!message) return util.fail(ctx, '消息不存在或已被删除');
	util.success(ctx, message);
}

async function getUserUnreadCount(ctx) {
	const { userId } = util.decodeToken(ctx);

	const result = await MessageService.getUserUnreadCount(userId);

	util.success(ctx, result);
}

async function updatePublishStatus(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { id, isPublished } = ctx.request.body;

	if (!id || !['T', 'F'].includes(isPublished)) {
		return util.fail(ctx, '消息ID或发布状态无效');
	}

	const result = await MessageService.updatePublishStatus(id, isPublished, userId);
	util.success(ctx);
}
// 用户页面消息列表（个人消息 + 群发公告）
async function getUserMessages(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { page = 1, limit = 10, type, title } = ctx.query;

	const result = await MessageService.getUserMessages(userId, {
		page: +page,
		limit: +limit,
		type: type ? +type : undefined,
		title,
	});

	util.success(ctx, result);
}

async function updateMessageReadStatus(ctx) {
	const { userId } = util.decodeToken(ctx);
	const messages = ctx.request.body; // 接收数组 [{ id, type, status }, ...]

	if (!Array.isArray(messages) || messages.length === 0) {
		return util.fail(ctx, '消息列表无效');
	}

	try {
		await MessageService.updateMessageReadStatus(userId, messages);
		util.success(ctx);
	} catch (error) {
		util.fail(ctx, error.message || '更新失败');
	}
}

async function deleteUserMessage(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { ids } = ctx.request.body;

	// 参数验证
	if (!Array.isArray(ids) || ids.length === 0) {
		return util.fail(ctx, '消息 ID 列表无效');
	}

	try {
		await MessageService.deleteUserMessage(userId, ids);
		util.success(ctx, '');
	} catch (error) {
		console.error('Delete messages error:', error.message);
		util.fail(ctx, error.message || '删除失败');
	}
}
module.exports = {
	createMessage,
	listMessages,
	updateMessage,
	deleteMessage,
	getMessageById,
	getUserUnreadCount,
	updatePublishStatus,
	getUserMessages,
	updateMessageReadStatus,
	deleteUserMessage,
};
